package com.maigao.service;

import com.maigao.core.cache.JedisClient;
import com.maigao.core.cache.RedisKeyManager;
import com.maigao.core.exception.ServerCode;
import com.maigao.core.exception.ServerException;
import com.maigao.entity.TokenInfo;
import com.maigao.entity.jpa.User;
import com.maigao.util.uuid.IdUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Objects;

/**
 * @author awei
 * @description:
 * @date 2022/5/15 10:19 下午
 */
@Service
public class IdentifyService {
    @Autowired
    private JedisClient jedisClient;

    public TokenInfo getTokenInfo(String accessKey) {
        TokenInfo tokenInfo = jedisClient.get(RedisKeyManager.Auth.authKey(accessKey), TokenInfo.class);
        if (null == tokenInfo) {
            tokenInfo = new TokenInfo();
            tokenInfo.setLogin(false);
        }
        return tokenInfo;
    }

    public String saveLoginToken(User user) {
        if (Objects.isNull(user) || Objects.isNull(user.getId()) || Objects.isNull(user.getUid())) {
            throw new ServerException(ServerCode.SERVER_ERROR);
        }
        TokenInfo tokenInfo = new TokenInfo();
        tokenInfo.setLogin(true);
        tokenInfo.setUid(user.getUid());
        tokenInfo.setUserName(user.getUserName());
        tokenInfo.setMid(user.getId());

        String accessKey = IdUtils.fastSimpleUUID();

        // todo 登录时间暂存3天
        jedisClient.set(RedisKeyManager.Auth.authKey(accessKey), tokenInfo, LocalDateTime.now().plusDays(30));
        return accessKey;
    }
}
